﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ServiceConsumer;
using WSObjects;
using System.Xml.Serialization;
using System.Text;
using System.IO;

namespace NhaCungCap.Admin
{
    public partial class ChiTietDonDatHang : System.Web.UI.Page
    {
        public List<Province> list;
        public List<Transporttype> transporttype;
        public string link;
        public string serv_name;
        public string Prov_fr;
        public string Prov_t;
        public string serv;

        protected void Page_Load(object sender, EventArgs e)
        {
            SqlDataSource2.SelectCommand = "SELECT [code], ( select UserName FROM [aspnet_Users] where [DonDatHang].ID_aspUser = [aspnet_Users].UserId ) as  [IDUser], [ThoiDiemLapDDH], [TongTien], [SoDienThoaiNguoiNhan], [DiaChiGiaoHang], [EmailNguoiNhan], [TrangThai] FROM [DonDatHang] WHERE [DonDatHang].IDDonDatHang = " + Request.QueryString["ma"];
            ListView2.DataSource = SqlDataSource2;
            ListView2.DataBind();

            SqlDataSource1.SelectCommand = "SELECT [IDChiTietDDH], ( select TenTL FROM [TaiLieu] where [TaiLieu].IDTaiLieu = [ChiTietDDH].IDTaiLieu ) as [IDTaiLieu], [SoLuong], [DonGia] FROM [ChiTietDDH] WHERE IDDonDatHang = " + Request.QueryString["ma"];
            ListView1.DataSource = SqlDataSource1;
            ListView1.DataBind();


            if (!Page.IsPostBack)
            {
                for (int index = 1; index <= 24; index++)
                {
                    gio.Items.Add(index.ToString("00"));
                }
                for (int index = 1; index <= 60; index++)
                {
                    phut.Items.Add(index.ToString("00"));
                }
            }

        }
        public string format_text(string i)
        {
            string aa = "";

            if (i.CompareTo("0") == 0)
                aa = "Chưa duyệt";
            else
                if (i.CompareTo("1") == 0)
                    aa = "Đang giao hàng";
                else
                    aa = "Đã nhận tiền";
            return aa;
        }
        public string format_tt(string tt)
        {

            string rs = tt;
            //thay dau ',' thanh '.'
            int l = (rs.Length - 1) / 3;
            for (int i = 0; i < l; i++)
            {
                rs = rs.Insert(rs.Length - (i + 1) * 3 - i, ".");
            }

            return rs;
        }

        protected void DatLenhVanChuyen(object sender, EventArgs e)
        {
            /*int dem=0;
            int IDUser;
            String str="";
            
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                GridViewRow row = GridView1.Rows[i];
                bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;
                if (isChecked)
                {
                  dem ++;
                  str = GridView1.Rows[i].Cells[1].Text.ToString();
                }
            }

            if (dem == 1)
            {
                IDUser = Convert.ToInt32(str);
                Label1.Text = IDUser.ToString();
            }*/
           
            object[] reference4 = new object[8];
            reference4[0] = Session["SID"].ToString();
            //xu li dia chi gui
            reference4[1] = Prov_from.SelectedItem.Value;

            reference4[3] = addr_from.Text;

            //xl dia chi nhanl
            //  reference4[1] = list.Find(delegate(Province item) { return item.ProvinceName == Prov_t; }).ID;
            reference4[2] = Prov_to.SelectedItem.Value;

            reference4[4] = addr_to.Text;
            //xl service type
            //reference4[2] = transporttype.Find(delegate(Transporttype item) { return item.TransportTypeName == serv_type.SelectedItem.Value; }).ID; //serv_type.SelectedItem.Value;
            reference4[5] = serv_type.SelectedItem.Value;

            reference4[6] = ten_san_pham.Text + " : " + so_luong.Text;

            //xu li ep kieu du lieu sang datetime
            string MyString = Dated.Text + " " + gio.SelectedItem.Text + ":" + phut.SelectedItem.Text + ":00";
            DateTime time = DateTime.ParseExact(MyString, "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
            reference4[7] = time;

            object price = WSProxy.CallWebService(Session["link"].ToString(), Session["serv_name"].ToString(), "PlaceTransportCommand", reference4);
            if (price != null && price.ToString() != "-1")
            {
                //Result.Text = "Dat Hang Thanh Cong";
                //Result.Visible = true;
                Session["msg_type"] = "success";
                Session["msg"] = "Đã thực hiện đặt lệnh vận chuyển. Mã vận chuyển: " + price.ToString();
            }
            else
            {
                Session["msg_type"] = "error";
                Session["msg"] = "Đã xảy ra lỗi trong quá trình vận chuyển! Vui lòng thử lại hoặc chọn nhà vận chuyển khác!";
            }


        }

        protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
        {
            Prov_from.Items.Clear();
            Prov_to.Items.Clear();
            serv_type.Items.Clear();
            

            Prov_from.DataSource= null;Prov_from.DataBind();
            Prov_to.DataSource= null;Prov_to.DataBind();
            serv_type.DataSource = null; serv_type.DataBind();

            string value = DropDownList2.SelectedItem.Value;
            int i = value.IndexOf("???");
            int j = value.IndexOf("***");
            int k = value.IndexOf("^^^");
            int t = value.IndexOf("$$$");



            string ma = value.Substring(0, i);
            link = value.Substring(i + 3, j - i - 3);
            serv_name = value.Substring(j + 3, k - j - 3);
            string user_name = value.Substring(k + 3, t - k - 3);
            string password = value.Substring(t + 3);

            Session["link"] = link;
            Session["serv_name"] = serv_name;
            //addr_from.Text = "co vao" + link  + serv_name + user_name + password;
            // addr_from.Visible = true;

            object[] reference = new object[2];
            reference[0] = user_name;
            reference[1] = password;

            object s = WSProxy.CallWebService(link, serv_name, "WSLogin", reference);
            //object s = WSProxy.CallWebService(Session["link"].ToString(), Session["serv_name"].ToString(), "WSLogin", reference);
            if (s.ToString() == "-1")
            {
                Session["msg_type"] = "error";
                Session["msg"] = "Kết nối web service bị lỗi";
                return;
            }
            Session["SID"] = s.ToString();

            object[] temp = new object[0];

            object s_provine = WSProxy.CallWebService(link, serv_name, "GetProvinceName", temp);

            list = ConvertType<List<Province>>(s_provine);
            if (s_provine != null)
            {

                for (j = 0; j < list.Count; j++)
                {
                    Prov_from.Items.Add(new ListItem(list[j].ProvinceName, list[j].ID));
                    Prov_to.Items.Add(new ListItem(list[j].ProvinceName, list[j].ID));
                }

                Prov_from.Visible = true;
                Prov_to.Visible = true;
            }



            //object s_service_type = WSProxy.CallWebService(Session["link"].ToString(), Session["serv_name"].ToString(), "GetTransportType", temp);
            object s_service_type = WSProxy.CallWebService(link, serv_name, "GetTransportType", temp);


            transporttype = ConvertType<List<Transporttype>>(s_service_type);
            if (s_service_type != null)
            {
                for (j = 0; j < transporttype.Count; j++)
                {
                    serv_type.Items.Add(new ListItem(transporttype[j].TransportTypeName, transporttype[j].ID));
                }
                serv_type.Visible = true;
            }

            Button3.Visible = true;


        }

        public T ConvertType<T>(object input)
        {

            XmlSerializer serializer = new XmlSerializer(input.GetType(), "http://tempuri.org/");
            XmlSerializer deserializer = new XmlSerializer(typeof(T), "http://tempuri.org/");

            StringBuilder sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb))
            {
                serializer.Serialize(sw, input);
            }

            using (StringReader sr = new StringReader(sb.ToString()))
            {
                return (T)deserializer.Deserialize(sr);
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            //xu li lay gia cua goi hang
            object[] reference4 = new object[4];
            /*
             Province tem = list.Find(delegate(Province item)
             {
                 return item.ProvinceName == Prov_fr;
             }
             );
             */

            //xu li dia chi gui
            reference4[0] = Prov_from.SelectedItem.Value; ;

            //xl dia chi nhanl
            //  reference4[1] = list.Find(delegate(Province item) { return item.ProvinceName == Prov_t; }).ID;
            reference4[1] = Prov_to.SelectedItem.Value; ;

            //xl service type
            //reference4[2] = transporttype.Find(delegate(Transporttype item) { return item.TransportTypeName == serv_type.SelectedItem.Value; }).ID; //serv_type.SelectedItem.Value;
            reference4[2] = serv_type.SelectedItem.Value;
            string tem = Session["link"].ToString();

            reference4[3] = ten_san_pham.Text + " : " + so_luong.Text;
            object price = WSProxy.CallWebService(Session["link"].ToString(), Session["serv_name"].ToString(), "ShippingPrice", reference4);
            if (price == null)
            {
                Session["msg_type"] = "error";
                Session["msg"] = "Đã có lỗi trong quá trình tính tiền!";
                tong_tien.Visible = true;
            }
            lb_tt.Visible = true;
            tong_tien.Text = price.ToString();
            tong_tien.Visible = true;

            //cho nay lam them cho cai ham PlaceTransportCommand, tham so reference lay them cai addr_from,addr_to,Prov_fr,Prov_t,ten_san_pham.Text + " : " + so_luong.Text;reference4[4](lay datetime)
            //xu li ep kieu du lieu sang datetime
            //string MyString = date.Text + " " + time.Text;
            //reference4[4] = DateTime.ParseExact(MyString, "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
            //object price = WSProxy.CallWebService(Session["link"].ToString(), Session["serv_name"].ToString(), "PlaceTransportCommand", reference4);
        }
        protected void Button2_Click1(object sender, EventArgs e)
        {
            van_chuyen.Visible = true;
        }
}
}